package cn.itcast.demo.mq.topic;

import cn.itcast.demo.mq.utils.ConnectionUtils;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.ConfirmListener;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.MessageProperties;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 发送者
 *
 * @author 虎哥
 */
public class SendDemo {
    public static final String EXCHANGE_NAME = "topic.exchange";
    public static final String QUEUE1_NAME = "topic.queue1";
    public static final String QUEUE2_NAME = "topic.queue2";

    public static void main(String[] args) throws IOException, TimeoutException {
        // 建立连接
        Connection connection = ConnectionUtils.getConnection();
        // 获取通道Channel
        Channel channel = connection.createChannel();
        // 创建交换机
        channel.exchangeDeclare(EXCHANGE_NAME, "topic", true);
        // 开启生产者确认
        channel.confirmSelect();

        // 发送消息
        String message = "中国新冠肺炎新增0，疫情得到完美控制，可以去电影院了!";
        channel.basicPublish(EXCHANGE_NAME, "china.news", MessageProperties.PERSISTENT_TEXT_PLAIN, message.getBytes());

       /* try {
            channel.waitForConfirmsOrDie(5_000);
        } catch (InterruptedException e) {
            System.out.println("消息发送失败，可以重发");
        }*/
        channel.addConfirmListener(new ConfirmListener() {
            @Override
            public void handleAck(long deliveryTag, boolean multiple) throws IOException {
                System.out.println("消息发送成功了！");
            }

            @Override
            public void handleNack(long deliveryTag, boolean multiple) throws IOException {
                System.out.println("消息发送失败了！重发消息");
            }
        });

        System.out.println("消息已经发送： " + message);

        // 关闭连接和通道
        channel.close();
        connection.close();
    }
}
